package jafou.client.ui.objects;

import jafou.client.remote.JafouService;
import jafou.client.remote.JafouServiceAsync;
import jafou.client.ui.ForumWidget;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.Tree;
import com.google.gwt.user.client.ui.TreeItem;

public class ForumsTree extends Tree {
	
	private ForumWidget ui;
	
	private final JafouServiceAsync handler = GWT.create(JafouService.class);
	
	private String[][] forums = null;
	private TreeItem forumsItem = null;
	
	private class ForumClickHandler implements ClickHandler {
		private String forumId;
		
		public ForumClickHandler(String forumId){
			this.forumId = forumId;
		}

		@Override
		public void onClick(ClickEvent event) {
			handleClickOnForum(forumId);
		}
		
	}
	
	private AsyncCallback<String[][]> updateCallback = new AsyncCallback<String[][]>() {

		@Override
		public void onFailure(Throwable caught) {
			doUpdateOnFailure();
		}

		@Override
		public void onSuccess(String[][] result) {
			forums = result;
			doUpdateOnSuccess();
		}
		
	};
	
	public ForumsTree(ForumWidget ui) {
		this.ui = ui;
		TreeItem forumsItem = new TreeItem("Forums");
		this.forumsItem = forumsItem;
		addItem(forumsItem);
		update();
	}
	
	public void update() {
		handler.getForums(updateCallback);
	}
	
	private void doUpdateOnSuccess() {
		if(forums == null) {return;}
		if(forumsItem == null) {
			forumsItem = new TreeItem("Forums");
			addItem(forumsItem);
		} else {
			forumsItem.removeItems();
		}
		for(int i=0; i<forums.length; i++) {
			HTML html = new HTML(forums[i][0]);
			html.addClickHandler(new ForumClickHandler(forums[i][1]));
			forumsItem.addItem(new TreeItem(html));
		}
		forumsItem.setState(true);
	}
	
	private void doUpdateOnFailure() {
		
	}
	
	private void handleClickOnForum(String forumId) {
		ui.renderForum(forumId);
	}

}
